using MediatR;
using ProduceBasicData.Api.Application.Command.Material.ProductMaterial;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.ProductMaterial
{
    /// <summary>
    /// 产品物料查询处理类
    /// </summary>
    public class GetProductMaterialHandler : IRequestHandler<GetProductMaterialCommand, ApiPaging<ProductMaterialDTO>>
    {
        private readonly IBaseRespository<ProductMaterialModel> productMaterialRepository;
        private readonly IBaseRespository<GroupTypeDictionary> groupTypeRepository;
        private readonly IBaseRespository<CraftModel> craftRepository;

        public GetProductMaterialHandler(
            IBaseRespository<ProductMaterialModel> productMaterialRepository,
            IBaseRespository<GroupTypeDictionary> groupTypeRepository,
            IBaseRespository<CraftModel> craftRepository)
        {
            this.productMaterialRepository = productMaterialRepository;
            this.groupTypeRepository = groupTypeRepository;
            this.craftRepository = craftRepository;
        }

        public Task<ApiPaging<ProductMaterialDTO>> Handle(GetProductMaterialCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<ProductMaterialDTO>();

            try
            {
                // 获取产品物料数据
                var productMaterials = productMaterialRepository.GetAll().Where(x => !x.Isdel);
                var groupTypes = groupTypeRepository.GetAll().Where(x => !x.Isdel);
                var crafts = craftRepository.GetAll().Where(x => !x.Isdel);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.ProductNo))
                {
                    productMaterials = productMaterials.Where(x => x.ProductNo.Contains(request.ProductNo));
                }

                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    productMaterials = productMaterials.Where(x => x.ProductName.Contains(request.ProductName));
                }

                if (request.GroupTypeId.HasValue)
                {
                    productMaterials = productMaterials.Where(x => x.GroupTypeId == request.GroupTypeId.Value);
                }

                if (request.GroupId.HasValue)
                {
                    productMaterials = productMaterials.Where(x => x.GroupId == request.GroupId.Value);
                }

                // 联表查询
                var query = from pm in productMaterials
                           join gt in groupTypes on pm.GroupTypeId equals gt.Id into groupTypeGroup
                           from groupType in groupTypeGroup.DefaultIfEmpty()
                           join c in crafts on pm.DefaultCraftId equals c.Id into craftGroup
                           from craft in craftGroup.DefaultIfEmpty()
                           select new ProductMaterialDTO
                           {
                               Id = pm.Id,
                               ProductNo = pm.ProductNo,
                               ProductName = pm.ProductName,
                               Specification = pm.Specification,
                               Unit = pm.Unit,
                               WarningValue = pm.WarningValue,
                               GroupTypeId = pm.GroupTypeId,
                               GroupType = groupType != null ? groupType.GroupTypeName : pm.GroupType,
                               GroupId = pm.GroupId,
                               GroupName = pm.GroupName,
                               DefaultCraftId = pm.DefaultCraftId,
                               DefaultCraftName = craft != null ? craft.CraftName : pm.DefaultCraftName,
                               ProductDesc = pm.ProductDesc,
                               CreateName = pm.CreateName,
                               CreateTime = pm.CreateTime,
                               UpdateName = pm.UpdateName,
                               UpdateTime = pm.UpdateTime
                           };

                // 分页处理
                result.PageDatas = query
                    .OrderByDescending(x => x.CreateTime)
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();

                result.TotalCount = query.Count();
                result.Code = ApiEnum.Success;
                result.Msg = "产品物料查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"产品物料查询异常：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
}
